home *** CD-ROM | disk | FTP | other *** search
/ Linux Cubed Series 7: Sunsite / Linux Cubed Series 7 - Sunsite Vol 1.iso / system / network / file-tra / fsp-2.7 / fsp-2 / fsp / common / random.c < prev    next >
Encoding:
C/C++ Source or Header  |  1993-04-23  |  12.4 KB  |  334 lines

  1. /*
  2.  * Copyright (c) 1983 Regents of the University of California.
  3.  * All rights reserved.
  4.  *
  5.  * Redistribution and use in source and binary forms are permitted
  6.  * provided that: (1) source distributions retain this entire copyright
  7.  * notice and comment, and (2) distributions including binaries display
  8.  * the following acknowledgement:  ``This product includes software
  9.  * developed by the University of California, Berkeley and its contributors''
  10.  * in the documentation or other materials provided with the distribution
  11.  * and in all advertising materials mentioning features or use of this
  12.  * software. Neither the name of the University nor the names of its
  13.  * contributors may be used to endorse or promote products derived
  14.  * from this software without specific prior written permission.
  15.  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
  16.  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
  17.  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
  18.  */
  19.  
  20. #if defined(LIBC_SCCS) && !defined(lint)
  21. static char sccsid[] = "@(#)random.c    5.7 (Berkeley) 6/1/90";
  22. #endif /* LIBC_SCCS and not lint */
  23.  
  24. #include "tweak.h"
  25. #include <stdio.h>
  26.  
  27. #ifdef NEED_RANDOM
  28. /*
  29.  * random.c:
  30.  * An improved random number generation package.  In addition to the standard
  31.  * rand()/srand() like interface, this package also has a special state info
  32.  * interface.  The initstate() routine is called with a seed, an array of
  33.  * bytes, and a count of how many bytes are being passed in; this array is then
  34.  * initialized to contain information for random number generation with that
  35.  * much state information.  Good sizes for the amount of state information are
  36.  * 32, 64, 128, and 256 bytes.  The state can be switched by calling the
  37.  * setstate() routine with the same array as was initiallized with initstate().
  38.  * By default, the package runs with 128 bytes of state information and
  39.  * generates far better random numbers than a linear congruential generator.
  40.  * If the amount of state information is less than 32 bytes, a simple linear
  41.  * congruential R.N.G. is used.
  42.  * Internally, the state information is treated as an array of longs; the
  43.  * zeroeth element of the array is the type of R.N.G. being used (small
  44.  * integer); the remainder of the array is the state information for the
  45.  * R.N.G.  Thus, 32 bytes of state information will give 7 longs worth of
  46.  * state information, which will allow a degree seven polynomial.  (Note: the 
  47.  * zeroeth word of state information also has some other information stored
  48.  * in it -- see setstate() for details).
  49.  * The random number generation technique is a linear feedback shift register
  50.  * approach, employing trinomials (since there are fewer terms to sum up that
  51.  * way).  In this approach, the least significant bit of all the numbers in
  52.  * the state table will act as a linear feedback shift register, and will have
  53.  * period 2^deg - 1 (where deg is the degree of the polynomial being used,
  54.  * assuming that the polynomial is irreducible and primitive).  The higher
  55.  * order bits will have longer periods, since their values are also influenced
  56.  * by pseudo-random carries out of the lower bits.  The total period of the
  57.  * generator is approximately deg*(2**deg - 1); thus doubling the amount of
  58.  * state information has a vast influence on the period of the generator.
  59.  * Note: the deg*(2**deg - 1) is an approximation only good for large deg,
  60.  * when the period of the shift register is the dominant factor.  With deg
  61.  * equal to seven, the period is actually much longer than the 7*(2**7 - 1)
  62.  * predicted by this formula.
  63.  */
  64.  
  65. /*
  66.  * For each of the currently supported random number generators, we have a
  67.  * break value on the amount of state information (you need at least this
  68.  * many bytes of state info to support this random number generator), a degree
  69.  * for the polynomial (actually a trinomial) that the R.N.G. is based on, and
  70.  * the separation between the two lower order coefficients of the trinomial.
  71.  */
  72.  
  73. #define    TYPE_0 0 /* linear congruential */
  74. #define    BREAK_0 8
  75. #define    DEG_0 0
  76. #define    SEP_0 0
  77.      
  78. #define    TYPE_1 1 /* x**7 + x**3 + 1 */
  79. #define    BREAK_1 32
  80. #define    DEG_1 7
  81. #define    SEP_1 3
  82.  
  83. #define    TYPE_2 2 /* x**15 + x + 1 */
  84. #define    BREAK_2 64
  85. #define    DEG_2 15
  86. #define    SEP_2 1
  87.  
  88. #define    TYPE_3 3 /* x**31 + x**3 + 1 */
  89. #define    BREAK_3 128
  90. #define    DEG_3 31
  91. #define    SEP_3 3
  92.  
  93. #define    TYPE_4 4 /* x**63 + x + 1 */
  94. #define    BREAK_4 256
  95. #define    DEG_4 63
  96. #define    SEP_4 1
  97.  
  98. /*
  99.  * Array versions of the above information to make code run faster -- relies
  100.  * on fact that TYPE_i == i.
  101.  */
  102.  
  103. #define    MAX_TYPES 5 /* max number of types above */
  104.  
  105. static int degrees[MAX_TYPES] = {DEG_0, DEG_1, DEG_2, DEG_3, DEG_4};
  106. static int seps[MAX_TYPES] = {SEP_0, SEP_1, SEP_2, SEP_3, SEP_4};
  107.      
  108. /*
  109.  * Initially, everything is set up as if from :
  110.  *        initstate( 1, &randtbl, 128 );
  111.  * Note that this initialization takes advantage of the fact that srandom()
  112.  * advances the front and rear pointers 10*rand_deg times, and hence the
  113.  * rear pointer which starts at 0 will also end up at zero; thus the zeroeth
  114.  * element of the state information, which contains info about the current
  115.  * position of the rear pointer is just
  116.  *    MAX_TYPES*(rptr - state) + TYPE_3 == TYPE_3.
  117.  */
  118.      
  119. static long randtbl[DEG_3+1] = {TYPE_3,
  120.                   0x9a319039, 0x32d9c024, 0x9b663182, 
  121.                   0x5da1f342, 0xde3b81e0, 0xdf0a6fb5,
  122.                   0xf103bc02, 0x48f340fb, 0x7449e56b,
  123.                   0xbeb1dbb0, 0xab5c5918, 0x946554fd,
  124.                   0x8c2e680f, 0xeb3d799f, 0xb11ee0b7,
  125.                   0x2d436b86, 0xda672e2a, 0x1588ca88,
  126.                   0xe369735d, 0x904f35f7, 0xd7158fd6,
  127.                   0x6fa6f051, 0x616e6b96, 0xac94efdc, 
  128.                   0x36413f93, 0xc622c298, 0xf5a42ab8,
  129.                   0x8a88d77b, 0xf5ad9d0e, 0x8999220b,
  130.                   0x27fb47b9 };
  131.      
  132. /*
  133.  * fptr and rptr are two pointers into the state info, a front and a rear
  134.  * pointer.  These two pointers are always rand_sep places aparts, as they
  135.  * cycle cyclically through the state information.  (Yes, this does mean we
  136.  * could get away with just one pointer, but the code for random() is more
  137.  * efficient this way).  The pointers are left positioned as they would be
  138.  * from the call initstate( 1, randtbl, 128 ) (The position of the rear
  139.  * pointer, rptr, is really 0 (as explained above in the initialization of
  140.  * randtbl) because the state table pointer is set to point to randtbl[1]
  141.  * (as explained below).
  142.  */
  143.      
  144. static long *fptr = &randtbl[SEP_3+1];
  145. static long *rptr = &randtbl[1];
  146.  
  147. /*
  148.  * The following things are the pointer to the state information table,
  149.  * the type of the current generator, the degree of the current polynomial
  150.  * being used, and the separation between the two pointers.
  151.  * Note that for efficiency of random(), we remember the first location of
  152.  * the state information, not the zeroeth.  Hence it is valid to access
  153.  * state[-1], which is used to store the type of the R.N.G.
  154.  * Also, we remember the last location, since this is more efficient than
  155.  * indexing every time to find the address of the last element to see if
  156.  * the front and rear pointers have wrapped.
  157.  */
  158.  
  159. static long *state = &randtbl[ 1 ];
  160. static int rand_type = TYPE_3;
  161. static int rand_deg = DEG_3;
  162. static int rand_sep = SEP_3;
  163. static long *end_ptr = &randtbl[ DEG_3 + 1 ];
  164.  
  165. /*
  166.  * srandom:
  167.  * Initialize the random number generator based on the given seed.  If the
  168.  * type is the trivial no-state-information type, just remember the seed.
  169.  * Otherwise, initializes state[] based on the given "seed" via a linear
  170.  * congruential generator.  Then, the pointers are set to known locations
  171.  * that are exactly rand_sep places apart.  Lastly, it cycles the state
  172.  * information a given number of times to get rid of any initial dependencies
  173.  * introduced by the L.C.R.N.G.
  174.  * Note that the initialization of randtbl[] for default usage relies on
  175.  * values produced by this routine.
  176.  */
  177.  
  178. void srandom PROTO1(unsigned int, x)
  179. {
  180.   register  int        i, j;
  181.   long random();
  182.   
  183.   if(rand_type == TYPE_0) state[0] = x;
  184.   else {
  185.     j = 1;
  186.     state[0] = x;
  187.     for(i = 1; i < rand_deg; i++)  {
  188.       state[i] = 1103515245*state[i - 1] + 12345;
  189.     }
  190.     fptr = &state[rand_sep];
  191.     rptr = &state[0];
  192.     for(i = 0; i < 10*rand_deg; i++) random();
  193.   }
  194. }
  195.  
  196. /*
  197.  * initstate:
  198.  * Initialize the state information in the given array of n bytes for
  199.  * future random number generation.  Based on the number of bytes we
  200.  * are given, and the break values for the different R.N.G.'s, we choose
  201.  * the best (largest) one we can and set things up for it.  srandom() is
  202.  * then called to initialize the state information.
  203.  * Note that on return from srandom(), we set state[-1] to be the type
  204.  * multiplexed with the current value of the rear pointer; this is so
  205.  * successive calls to initstate() won't lose this information and will
  206.  * be able to restart with setstate().
  207.  * Note: the first thing we do is save the current state, if any, just like
  208.  * setstate() so that it doesn't matter when initstate is called.
  209.  * Returns a pointer to the old state.
  210.  */
  211.  
  212. char * initstate PROTO3(unsigned int, seed, char *, arg_state, int, n )
  213. {
  214.   register char *ostate = (char *)(&state[-1]);
  215.   
  216.   if(rand_type  ==  TYPE_0)  state[-1] = rand_type;
  217.   else state[-1] = MAX_TYPES*(rptr - state) + rand_type;
  218.   if(n < BREAK_1)  {
  219.     if(n < BREAK_0)  {
  220.       fprintf(stderr,"initstate: not enough state (%d bytes); ignored.\n", n);
  221.       return 0;
  222.     }
  223.     rand_type = TYPE_0;
  224.     rand_deg = DEG_0;
  225.     rand_sep = SEP_0;
  226.   } else {
  227.     if(n < BREAK_2) {
  228.       rand_type = TYPE_1;
  229.       rand_deg = DEG_1;
  230.       rand_sep = SEP_1;
  231.     } else {
  232.       if(n < BREAK_3) {
  233.     rand_type = TYPE_2;
  234.     rand_deg = DEG_2;
  235.     rand_sep = SEP_2;
  236.       } else {
  237.     if(n < BREAK_4) {
  238.       rand_type = TYPE_3;
  239.       rand_deg = DEG_3;
  240.       rand_sep = SEP_3;
  241.     } else {
  242.       rand_type = TYPE_4;
  243.       rand_deg = DEG_4;
  244.       rand_sep = SEP_4;
  245.     }
  246.       }
  247.     }
  248.   }
  249.   state = &(((long *)arg_state)[1]);    /* first location */
  250.   end_ptr = &state[rand_deg];    /* must set end_ptr before srandom */
  251.   srandom(seed);
  252.   if(rand_type == TYPE_0) state[-1] = rand_type;
  253.   else state[-1] = MAX_TYPES*(rptr - state) + rand_type;
  254.   return(ostate);
  255. }
  256.  
  257. /*
  258.  * setstate:
  259.  * Restore the state from the given state array.
  260.  * Note: it is important that we also remember the locations of the pointers
  261.  * in the current state information, and restore the locations of the pointers
  262.  * from the old state information.  This is done by multiplexing the pointer
  263.  * location into the zeroeth word of the state information.
  264.  * Note that due to the order in which things are done, it is OK to call
  265.  * setstate() with the same state as the current state.
  266.  * Returns a pointer to the old state information.
  267.  */
  268.  
  269. char *setstate PROTO1(char *, arg_state)
  270. {
  271.   register long    *new_state = (long *)arg_state;
  272.   register int type = new_state[0]%MAX_TYPES;
  273.   register int rear = new_state[0]/MAX_TYPES;
  274.   char *ostate = (char *)(&state[-1]);
  275.   
  276.   if(rand_type == TYPE_0)  state[-1] = rand_type;
  277.   else  state[-1] = MAX_TYPES*(rptr - state) + rand_type;
  278.   switch(type) {
  279.     case  TYPE_0:
  280.     case  TYPE_1:
  281.     case  TYPE_2:
  282.     case  TYPE_3:
  283.     case  TYPE_4:
  284.       rand_type = type;
  285.       rand_deg = degrees[type];
  286.       rand_sep = seps[type];
  287.       break;
  288.     default:
  289.       fprintf(stderr,"setstate: state info has been munged; not changed.\n");
  290.   }
  291.   state = &new_state[1];
  292.   if(rand_type != TYPE_0) {
  293.     rptr = &state[rear];
  294.     fptr = &state[(rear + rand_sep)%rand_deg];
  295.   }
  296.   end_ptr = &state[rand_deg]; /* set end_ptr too */
  297.   return(ostate);
  298. }
  299.  
  300. /*
  301.  * random:
  302.  * If we are using the trivial TYPE_0 R.N.G., just do the old linear
  303.  * congruential bit.  Otherwise, we do our fancy trinomial stuff, which is the
  304.  * same in all ther other cases due to all the global variables that have been
  305.  * set up.  The basic operation is to add the number at the rear pointer into
  306.  * the one at the front pointer.  Then both pointers are advanced to the next
  307.  * location cyclically in the table.  The value returned is the sum generated,
  308.  * reduced to 31 bits by throwing away the "least random" low bit.
  309.  * Note: the code takes advantage of the fact that both the front and
  310.  * rear pointers can't wrap on the same call by not testing the rear
  311.  * pointer if the front one has wrapped.
  312.  * Returns a 31-bit random number.
  313.  */
  314.  
  315. long random PROTO0((void))
  316. {
  317.   long i;
  318.   
  319.   if(rand_type == TYPE_0) {
  320.     i = state[0] = (state[0]*1103515245 + 12345)&0x7fffffff;
  321.   } else  {
  322.     *fptr += *rptr;
  323.     i = (*fptr >> 1)&0x7fffffff; /* chucking least random bit */
  324.     if(++fptr >= end_ptr) {
  325.       fptr = state;
  326.       ++rptr;
  327.     } else  {
  328.       if(++rptr >= end_ptr) rptr = state;
  329.     }
  330.   }
  331.   return(i);
  332. }
  333. #endif /* NEED_RANDOM */
  334.